package com.example.demo.register.captcha;

import com.example.demo.constants.DemoConstants;
import com.google.code.kaptcha.Producer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
public class CaptchaServiceImpl implements CaptchaService {
    @Value("${demo.commonCode.type}")
    String type;
    @Resource(name = "captchaProducer")
    private Producer captchaProducer;
    @Resource(name = "captchaProducerMath")
    private Producer captchaProducerMath;
    @Autowired
    StringRedisTemplate redisTemplate;

    @Override
    public String generateCode(HttpServletResponse response) throws IOException {
        // 保存验证码信息
        String uuid = String.valueOf(UUID.randomUUID());
        String verifyKey = DemoConstants.REDIS_KEY_CODE_COMMON + uuid;

        String capStr = null, code = null;
        BufferedImage image = null;

        // 生成验证码
        if ("math".equals(type)) {
            String capText = captchaProducerMath.createText();
            capStr = capText.substring(0, capText.lastIndexOf("@"));
            code = capText.substring(capText.lastIndexOf("@") + 1);
            image = captchaProducerMath.createImage(capStr);
        } else if ("char".equals(type)) {
            capStr = code = captchaProducer.createText();
            image = captchaProducer.createImage(capStr);
        }

        redisTemplate.opsForValue().set(verifyKey, code, 2, TimeUnit.MINUTES);
        // 转换流信息写出
//        FastByteArrayOutputStream os = new FastByteArrayOutputStream();
//        ImageIO.write(image, "jpg", os);
//        return Base64.encode(os.toByteArray());
        ImageIO.write(image, "jpg", response.getOutputStream());
        return uuid;
    }
}
